package com.endoc.news.netWoke;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.endoc.news.utils.TecentUtil;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetClient {

    private String TAG = "RXRETROFIT";
    private static final String BASE_URL = "http://service-o5ikp40z-1255468759.ap-shanghai.apigateway.myqcloud.com/";
    private static final int OKHTTP_TIMEOUT = 10;
    private static NetClient util;
    private Retrofit retrofit;
    private Context context;
 /*   @Override
    public String getFormal() {
        return "http://service-o5ikp40z-1255468759.ap-shanghai.apigateway.myqcloud.com/";
    }

    @Override
    public String getTest() {
        return "http://service-o5ikp40z-1255468759.ap-shanghai.apigateway.myqcloud.com/";
    }*/

    protected Interceptor getInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                //请求前,在所有请求中添加参数
                String timeStr = TecentUtil.getTimeStr();
                Request.Builder builder = chain.request().newBuilder();
                builder.addHeader("Source", "source");
                builder.addHeader("Authorization", TecentUtil.getAuthorization(timeStr));
                builder.addHeader("Date", timeStr);

                //执行请求
                Response proceed = chain.proceed(builder.build());

                //得到请求后Response对象,此处可以对Response进行,然后再将response传递下去
                Logger.d("body=="+proceed.body());

                //将response传递下去
                return proceed;
            }
        };
    }






    public NetClient() {
       /* context = Application.getContexts();
        Interceptor interceptor = new Interceptor() {
            @NotNull
            @Override
            public Response intercept(@NotNull Chain chain) throws IOException {
                Request original = chain.request();
                HttpUrl url = original.url().newBuilder()
                        .addQueryParameter("token", SpUtils.getSPUtil(context).getString("token", ""))
                        .build();

                Request request = original.newBuilder()
                        .url(url)
                        .build();

                long start_time = System.currentTimeMillis();
                Response response = chain.proceed(request);
                long end_time = System.currentTimeMillis();
                long duration = end_time - start_time;
                MediaType mediaType = response.body().contentType();
                String content = response.body().string();
                Log.e(TAG, "----------Request Start----------------");
                Log.e(TAG, "| " + request.toString() + request.headers().toString());
                Log.e(TAG, "| Response:" + content);
                Log.e(TAG, "----------Request End:" + duration + "毫秒----------");
                return response.newBuilder()
                        .body(ResponseBody.create(mediaType, content))
                        .build();
            }
        };*/
        /**
         * OKHttp默认三个超时时间是10s，有些请求时间比较长，需要重新设置下
         */


        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(OKHTTP_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(OKHTTP_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(OKHTTP_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(getInterceptor())
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(httpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static NetClient getInstance() {
        if (util == null) {
            synchronized (NetClient.class) {
                if (util == null) {
                    util = new NetClient();
                }
            }
        }
        return util;
    }

    public <T> T getApiService(Class<T> apiServer) {
        return retrofit.create(apiServer);
    }

    /**
     * 得到ObservableTransformer对象
     * @param observer 观察者
     * @param <T> 泛型
     * @return
     */
    public <T> ObservableTransformer<T, T> getObservableTransformer(final Observer<T> observer){
        ObservableTransformer<T, T> observableTransformer = new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                Observable<T> newsChannelsBeanObservable = upstream.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread());
                newsChannelsBeanObservable.subscribe(observer);
                return newsChannelsBeanObservable;
            }
        };
        return observableTransformer;
    }
}
